package il.yifanantonio.tagsonomy;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;

/**
 *
 */
public class Main {
	private static final Logger LOG = Logger.getLogger(Initiative.class
			.getName());
	/**
	 * it gets the information of the initiatives listed in initiativesEs.txt 
	 * and save them in initiatives.dat file
	 * @param args
	 */
public static void main(String[] args){
	List<Initiative> is = getInitiatives();
	saveInitiatives("initiatives.dat",is);
	List<Initiative> is2 = getInitiatives("initiatives.dat");
	for (int i = 0; i<is2.size(); i++){
		LOG.info("Initiative: " + is2.get(i));
	}
}
	/**
	 * 
	 * @param file File where the initiative list is saved
	 * @return the list of initiatives listed in file
	 */

	public static List<Initiative> getInitiatives(String file) {
		List<Initiative> initiatives = new ArrayList<Initiative>();
		if (file == null)
			return getInitiatives();
		else{
			try{
			FileInputStream fis = new FileInputStream(file);
			ObjectInputStream in = new ObjectInputStream(fis);
			Initiative i = (Initiative) in.readObject();
			while (i!=null){
				initiatives.add(i);
				 i = (Initiative) in.readObject();
			}
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		return initiatives;
	}
	/**
	 * 
	 * @return the list of initiatives in p2pFoundation.net wiki 
	 * wiht names saved in initiativesEs.txt such that have more
	 * than one keyword 
	 */
	public static List<Initiative> getInitiatives() {
		List<Initiative> initiatives = new ArrayList<Initiative>();

		try {
			// Open the file with the list of initiatives
			FileInputStream fstream = new FileInputStream("initiativesEs.txt");
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;

			// Read File Line By Line
			while ((strLine = br.readLine()) != null) {
				try {

					URI uri = new URI("http", "p2pfoundation.net", "/"
							+ strLine, "");
					String url = uri.toString();
					// "http://p2pfoundation.net/"+URLEncoder.encode(strLine,"utf8")+"/es";
					LOG.finest("Visiting: " + url);
					// open the url
					org.jsoup.nodes.Document doc = Jsoup.connect(url).get();
					// String title = doc.title();
					String keywords = doc
							.select(":containsOwn(Palabras clave)").first()
							.parent().ownText();
					List<String> keywordList = Arrays.asList(keywords
							.split(", "));
					Element e = doc.select(":containsOwn(URL:)").first()
							.parent();
					String urlInitiative = e.getElementsByAttribute("href")
							.attr("href");
					LOG.info(urlInitiative);
					if (!keywordList.get(0).equals("")) {
						Initiative i = new Initiative(strLine, urlInitiative,
								keywordList);
						initiatives.add(i);
						LOG.finest("Adding initiative " + i.toString());
					} else {
						LOG.info("Initiative " + strLine
								+ " does not have keywords."
								+ " It will not be added");
					}
				} catch (Exception e) {
					System.err.println("Error: " + e.getMessage());
				}
			}
			// Close the input stream
			in.close();
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
		return initiatives;
	}

	static void saveInitiatives(String file, List<Initiative> initiatives) {
		try {
			FileOutputStream fos = new FileOutputStream(file);
			ObjectOutputStream o = new ObjectOutputStream(fos);
			for (int i = 0; i < initiatives.size(); i++)
				o.writeObject(initiatives.get(i));
			o.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
